package com.llk.myIoLearn.reactorBase;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ss = ServerSocketChannel.open().bind(
                new InetSocketAddress(9090));
        final Selector selector = Selector.open();
        wuTiRaw(selector);
        while (true) {
            SocketChannel channel = ss.accept();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            System.out.println("register channel: " + channel.getRemoteAddress());
        }
    }

    private static void wuTiRaw(final Selector selector) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        selector.select();
                        Set<SelectionKey> keys = selector
                                .selectedKeys();
                        Iterator<SelectionKey> it = keys.iterator();
                        while (it.hasNext()) {
                            SelectionKey next = it.next();
                            if (next.isReadable()) {
                                ByteBuffer bb = ByteBuffer.allocate(10);
                                SocketChannel channel = (SocketChannel) next
                                        .channel();
                                channel.read(bb);
                                System.out.println(bb.toString());

                            }
                            it.remove();
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                }

            }
        });
        t.start();
    }
}